import sys
import time
import threading
import pyautogui
import pyperclip
import pygetwindow as gw
from pynput import mouse
from PyQt5.QtWidgets import (
    QApplication, QWidget, QLabel, QLineEdit, QPushButton, QVBoxLayout, QMessageBox, QHBoxLayout, QProgressBar, QDialog, QGridLayout, QTabWidget, QSizePolicy
)
from PyQt5.QtCore import pyqtSignal, QObject, QThread, Qt, QUrl
from PyQt5.QtGui import QFont
from PyQt5.Qt import QDesktopServices  # 正确的导入位置

### 1. **RecordingThread 类**
class RecordingThread(QThread):
    position_recorded = pyqtSignal(tuple)

    def __init__(self):
        super().__init__()
        self.position = None
        self.listener = None

    def run(self):
        def on_click(x, y, button, pressed):
            if pressed and button == mouse.Button.right:  # 使用右键点击
                self.position = (x, y)
                self.position_recorded.emit(self.position)
                self.listener.stop()

        self.listener = mouse.Listener(on_click=on_click)
        self.listener.start()
        self.listener.join()

### 2. **Worker 类（点击任务）**
class ClickWorker(QObject):
    progress = pyqtSignal(int)
    finished = pyqtSignal()

    def __init__(self, positions, count, interval):
        super().__init__()
        self.positions = positions
        self.count = count
        self.interval = interval

    def run(self):
        try:
            for i in range(self.count):
                for position in self.positions:
                    pyautogui.click(position, button='left')  # 使用左键点击
                time.sleep(self.interval)
                self.progress.emit(int((i + 1) / self.count * 100))
            self.finished.emit()
        except Exception as e:
            print(f"Error in click worker thread: {e}")
            self.finished.emit()

### 3. **Worker 类（输入任务）**
class InputWorker(QObject):
    progress = pyqtSignal(int)
    finished = pyqtSignal()

    def __init__(self, app_title, count, task):
        super().__init__()
        self.app_title = app_title
        self.count = count
        self.task = task

    def run(self):
        try:
            app_window = gw.getWindowsWithTitle(self.app_title)[0]
            if not app_window.isActive:
                app_window.activate()
                time.sleep(1)  # 等待窗口激活

            for i in range(self.count):
                print(f"执行任务：{self.task}，次数：{i + 1}")
                pyperclip.copy(self.task)
                pyautogui.hotkey('ctrl', 'v')
                time.sleep(0.5)
                pyautogui.press('enter')
                time.sleep(0.5)
                self.progress.emit(int((i + 1) / self.count * 100))
            self.finished.emit()
        except Exception as e:
            print(f"Error in input worker thread: {e}")
            self.finished.emit()

### 4. **AutoTaskApp 类**
class AutoTaskApp(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("自动化任务工具")
        self.setGeometry(100, 100, 400, 500)  # 初始窗口大小设置为400x500
        self.layout = QVBoxLayout()
        self.layout.setContentsMargins(10, 10, 10, 10)
        self.layout.setSpacing(10)

        # Tab 控件
        self.tabs = QTabWidget()
        self.tab1 = QWidget()
        self.tab2 = QWidget()
        self.tabs.addTab(self.tab1, "点击任务")
        self.tabs.addTab(self.tab2, "输入任务")
        self.layout.addWidget(self.tabs)

        # Tab 1: 点击任务
        self.tab1_layout = QGridLayout()
        self.tab1.setLayout(self.tab1_layout)

        # 提示信息
        self.instruction_label = QLabel("请按 '获取连点十字架' 按钮，然后右键点击屏幕上的任意位置来记录")
        self.tab1_layout.addWidget(self.instruction_label, 0, 0, 1, 2)

        # 鼠标点击位置输入框
        self.position_labels = []
        self.position_inputs = []
        for i in range(4):
            label = QLabel(f"位置 {i+1} (x, y):")
            input_field = QLineEdit()
            input_field.setReadOnly(True)
            input_field.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
            self.position_labels.append(label)
            self.position_inputs.append(input_field)
            self.tab1_layout.addWidget(label, i+1, 0)
            self.tab1_layout.addWidget(input_field, i+1, 1)

        # 任务次数输入
        self.count_label = QLabel("请输入任务执行的次数:")
        self.count_input = QLineEdit()
        self.count_input.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.tab1_layout.addWidget(self.count_label, 5, 0)
        self.tab1_layout.addWidget(self.count_input, 5, 1)

        # 间隔时间输入
        self.interval_label = QLabel("间隔时间 (秒):")
        self.interval_input = QLineEdit()
        self.interval_input.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.tab1_layout.addWidget(self.interval_label, 6, 0)
        self.tab1_layout.addWidget(self.interval_input, 6, 1)

        # 进度条
        self.click_progress_bar = QProgressBar()
        self.click_progress_bar.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.tab1_layout.addWidget(self.click_progress_bar, 7, 0, 1, 2)

        # 获取连点十字架按钮
        self.record_button = QPushButton("获取连点十字架")
        self.record_button.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.record_button.clicked.connect(self.start_recording)
        self.tab1_layout.addWidget(self.record_button, 8, 0)

        # 执行按钮
        self.click_execute_button = QPushButton("开始执行")
        self.click_execute_button.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.click_execute_button.clicked.connect(self.start_click_task)
        self.click_execute_button.setEnabled(False)
        self.tab1_layout.addWidget(self.click_execute_button, 8, 1)

        # 更新官网按钮
        self.update_button = QPushButton("访问更新官网")
        self.update_button.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.update_button.clicked.connect(self.open_update_website)
        self.tab1_layout.addWidget(self.update_button, 9, 0, 1, 2)

        # Tab 2: 输入任务
        self.tab2_layout = QVBoxLayout()
        self.tab2.setLayout(self.tab2_layout)

        # 目标应用程序名称输入
        self.app_label = QLabel("请输入目标应用程序的窗口标题:")
        self.app_input = QLineEdit()
        self.app_input.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.tab2_layout.addWidget(self.app_label)
        self.tab2_layout.addWidget(self.app_input)

        # 任务次数输入
        self.input_count_label = QLabel("请输入任务执行的次数:")
        self.input_count_input = QLineEdit()
        self.input_count_input.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.tab2_layout.addWidget(self.input_count_label)
        self.tab2_layout.addWidget(self.input_count_input)

        # 任务内容输入
        self.task_label = QLabel("请输入要执行的任务内容（示例：输入文本）:")
        self.task_input = QLineEdit()
        self.task_input.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.tab2_layout.addWidget(self.task_label)
        self.tab2_layout.addWidget(self.task_input)

        # 进度条
        self.input_progress_bar = QProgressBar()
        self.input_progress_bar.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.tab2_layout.addWidget(self.input_progress_bar)

        # 执行按钮
        self.input_execute_button = QPushButton("开始执行")
        self.input_execute_button.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.input_execute_button.clicked.connect(self.start_input_task)
        self.tab2_layout.addWidget(self.input_execute_button)

        self.setLayout(self.layout)

        self.positions = []
        self.recording_thread = None

        # 设置较大的初始字体大小
        self.font = QFont()
        self.font.setPointSize(14)  # 初始字体大小设置为14
        self.setFont(self.font)

        # 设置样式表
        self.setStyleSheet("""
            QWidget {
                font-size: 14pt;
            }
            QLabel {
                font-size: 14pt;
            }
            QLineEdit {
                font-size: 14pt;
                min-height: 30px;
            }
            QPushButton {
                font-size: 14pt;
                min-height: 30px;
            }
            QProgressBar {
                font-size: 14pt;
                min-height: 30px;
            }
        """)

        # 连接窗口大小变化信号
        self.resizeEvent = self.on_resize

    def on_resize(self, event):
        super().resizeEvent(event)
        new_size = event.size()
        width, height = new_size.width(), new_size.height()
        font_size = int((width + height) / 100)  # 根据窗口大小动态调整字体大小
        self.font.setPointSize(max(14, font_size))  # 保持最小字体大小为14
        self.setFont(self.font)

    def start_recording(self):
        if len(self.positions) >= 4:
            QMessageBox.warning(self, "警告", "最多支持4个位置。")
            return
        self.recording_thread = RecordingThread()
        self.recording_thread.position_recorded.connect(self.position_recorded)
        self.recording_thread.start()
        self.instruction_label.setText("请右键点击屏幕上的任意位置来记录")

    def position_recorded(self, position):
        self.positions.append(position)
        index = len(self.positions)
        self.position_inputs[index-1].setText(f"{position[0]}, {position[1]}")
        self.position_inputs[index-1].setReadOnly(False)
        if index == 4:
            self.record_button.setEnabled(False)
        self.click_execute_button.setEnabled(True)
        QMessageBox.information(self, "提示", f"已记录位置 {index}：{position}")

    def start_click_task(self):
        try:
            count = int(self.count_input.text())
            interval = float(self.interval_input.text())
        except ValueError:
            QMessageBox.warning(self, "警告", "请输入有效的数字作为点击次数和间隔时间。")
            return

        # 确认信息
        positions_str = ', '.join([f"({x}, {y})" for x, y in self.positions])
        confirm = QMessageBox.question(
            self, "确认", f"将在位置 {positions_str} 连续点击 {count} 次，每次间隔 {interval} 秒。确定吗？", QMessageBox.Yes | QMessageBox.No
        )
        if confirm == QMessageBox.No:
            return

        # 创建并启动工作线程
        self.click_worker = ClickWorker(self.positions, count, interval)
        self.click_worker.progress.connect(self.update_click_progress)
        self.click_worker.finished.connect(self.click_task_finished)
        threading.Thread(target=self.click_worker.run, daemon=True).start()

    def update_click_progress(self, value):
        self.click_progress_bar.setValue(value)

    def click_task_finished(self):
        QMessageBox.information(self, "完成", "点击任务执行完成。")
        self.positions = []
        for input_field in self.position_inputs:
            input_field.setReadOnly(True)
            input_field.clear()
        self.record_button.setEnabled(True)
        self.click_execute_button.setEnabled(False)

    def start_input_task(self):
        try:
            app_title = self.app_input.text()
            if not app_title:
                QMessageBox.warning(self, "警告", "请输入目标应用程序的窗口标题。")
                return

            count = int(self.input_count_input.text())
            task = self.task_input.text()
            if not task:
                QMessageBox.warning(self, "警告", "请输入要执行的任务内容。")
                return

            # 确认信息
            confirm = QMessageBox.question(
                self, "确认", f"将在应用程序 '{app_title}' 中执行 '{task}' 共 {count} 次。确定吗？", QMessageBox.Yes | QMessageBox.No
            )
            if confirm == QMessageBox.No:
                return

            # 创建并启动工作线程
            self.input_worker = InputWorker(app_title, count, task)
            self.input_worker.progress.connect(self.update_input_progress)
            self.input_worker.finished.connect(self.input_task_finished)
            threading.Thread(target=self.input_worker.run, daemon=True).start()
        except Exception as e:
            print(f"Error in start_input_task: {e}")

    def update_input_progress(self, value):
        self.input_progress_bar.setValue(value)

    def input_task_finished(self):
        QMessageBox.information(self, "完成", "输入任务执行完成。")
        self.app_input.clear()
        self.input_count_input.clear()
        self.task_input.clear()
        self.input_execute_button.setEnabled(True)

    def open_update_website(self):
        url = QUrl("https://www.123684.com/s/dk8iVv-BGuad")
        QDesktopServices.openUrl(url)

# 猫猫类
# 养只猫，希望代码不会出bug
# 　　　　　　 ＿＿
# 　　　　　／＞　　フ
# 　　　　　| 　_　 _ l
# 　 　　　／` ミ＿꒳ノ
# 　　 　 /　　　 　 |
# 　　　 /　 ヽ　　 ﾉ
# 　 　 │　　|　|　|
# 　／￣|　　 |　|　|
# 　| (￣ヽ＿_ヽ_)__)
# 　＼二つ

# 你的代码
print("感谢使用！😊")

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = AutoTaskApp()
    window.show()
    sys.exit(app.exec_())